<?php
declare (strict_types = 1);

namespace app\common\model\message;

use app\admin\traits\GetTableData;
use app\common\model\user\User;
use think\Model;

/**
 * @mixin think\Model
 */
class Message extends Model
{
    use GetTableData;

    const VISITED_NO = 1;
    const VISITED_YES = 2;

    // 设置字段信息
    protected $schema = [
        'id'            => 'int',
        'name'          => 'string',
        'email'         => 'string',
        'title'         => 'string',
        'message'       => 'string',
        'visited'       => 'int',
        'user_id'       => 'int',
        'create_time'   => 'int',
    ];

    // 类型转换
    protected $type = [
        'id'            => 'integer',
        'visited'       => 'integer',
        'user_id'       => 'integer',
    ];

    //插入之前完善数据
    public static function onBeforeInsert(Model $model)
    {
        $model->setAttr('user_id',app()->user->getId());
    }

    //关联用户
    public function user()
    {
        return $this->belongsTo(User::class,'user_id', 'id')->bind([
            'username' => 'showName',
            'avatar' => 'avatarUrl'
        ]);
    }

    //获取分类列表table数据
    public static function getListData(array $ruleWhere = []){
        //要查询的字段
        $fields = [
            'fields' =>['id','name', 'email','title','user_id','create_time'],
            'with' => ['user'],
            'withCount' => [],
        ];

        //(构建查询条件)
        $where = [];
        if ($start_time = input('start_time')){
            $where[] = ['create_time', '>=', strtotime($start_time)];
        }
        if ($end_time = input('end_time')){
            $where[] = ['create_time', '<=', strtotime( $end_time )];
        }
        if ($user_id = input('user_id/d')){
            $where[] = ['user_id','=',$user_id];
        }
        if ($visited = input('visited/d')){
            $where[] = ['visited','=',$visited];
        }

        //排序
        $order = ['id'=>'desc','create_time'=>'desc'];

        //[count:查询到的数目, list:记录列表]
        $data = static::operateDatum($where, $fields, $order,$ruleWhere);


        return [
            'count' => $data['count'],
            'data' => $data['list']
        ];
    }

}
